package org.fast.easy.oss.business.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.fast.easy.core.exception.ServiceException;
import org.fast.easy.core.util.StringUtils;
import org.fast.easy.framework.oss.core.OssClient;
import org.fast.easy.framework.oss.entity.UploadResult;
import org.fast.easy.framework.oss.factory.OssFactory;
import org.fast.easy.oss.domain.bo.SysOssBo;
import org.fast.easy.oss.domain.vo.RemoteFile;
import org.fast.easy.oss.business.IFileBusiness;
import org.fast.easy.oss.service.ISysOssService;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 类说明
 *
 * @author YanMing
 * @date 2024/5/17
 */
@Slf4j
@RequiredArgsConstructor
@Component
public class FileBusinessImpl implements IFileBusiness {


    private final ISysOssService sysOssService;

    /**
     * 文件上传请求
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public RemoteFile upload(String name, String originalFileName, String contentType, byte[] file) throws ServiceException {
        try {
            RemoteFile sysFile = null;
            if(StringUtils.isNotBlank(originalFileName) && file!=null) {
                String suffix = StringUtils.substring(originalFileName, originalFileName.lastIndexOf("."), originalFileName.length());
                OssClient storage = OssFactory.instance();
                UploadResult uploadResult = storage.uploadSuffix(file, suffix, contentType);
                // 保存文件信息
                SysOssBo oss = new SysOssBo();
                oss.setUrl(uploadResult.getUrl());
                oss.setFileSuffix(suffix);
                oss.setFileName(uploadResult.getFilename());
                oss.setOriginalName(originalFileName);
                oss.setService(storage.getConfigKey());
                if(sysOssService.insertByBo(oss)){
                    sysFile = new RemoteFile();
                    sysFile.setOssId(oss.getOssId());
                    sysFile.setName(uploadResult.getFilename());
                    sysFile.setUrl(uploadResult.getUrl());
                }

            }
            return sysFile;
        } catch (Exception e) {
            log.error("上传文件失败", e);
            throw new ServiceException("上传文件失败");
        }
    }

    /**
     * 通过ossId查询对应的url
     *
     * @param ossIds ossId串逗号分隔
     * @return url串逗号分隔
     */
    @Override
    public String selectUrlByIds(String ossIds) {
        return sysOssService.selectUrlByIds(ossIds);
    }
}
